<?php

namespace app\admin\controller\learn;

use app\admin\controller\Zlog;
use app\common\controller\Backend;
use app\common\logic\ChatManagerLogic;
use think\Cache;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 课程
 *
 * @icon fa fa-circle-o
 */
class Livecourse extends Backend
{
    
    /**
     * Course模型对象
     * @var \app\admin\model\learn\Course
     */
    protected $model = null;
    protected $model2 = null;
    protected $searchFields = 'icourse.d,course.name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\learn\Course;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isBuyList", $this->model->getIsBuyList());
        $this->view->assign("isShowPptList", $this->model->getIsShowPptList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2 = $this->getSelfDataWhere('course.org_cate_id');
            $total = $this->model
                ->with(['series'])
                    ->where($where)
                    ->where($where2)
                    ->where(['course.is_chat'=>1])
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                ->with(['series'])
                ->where(['course.is_chat'=>1])
                    ->where($where)
                    ->where($where2)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $key=>$row) {
                $row->sort = ($key+1+$offset);
//                $row->visible(['id','name','origin_price','price','visitor_origin_price','visitor_price','buy_numbers','image','thumbs','status','createtime']);
                
            }
            $list = collection($list)->toArray();
            if($list){
                foreach($list as &$val){
                    $info = Db::name('chat_room')->alias('r')->join('edu_chat_user u', 'u.id = r.talk_id', 'left')->where('edu_learn_course_id', $val['id'])->field('r.*,u.name as t_name,u.introduce')->find();
                    if($info){
                        $val['t_name'] = $info['t_name'];
                        $val['introduce'] = $info['introduce'];
                        $val['start_time'] = $info['start_time'];
                        $val['end_time'] = $info['end_time'];
                    }

                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try{
                    $params['org_cate_id'] = ORG_CATE_ID;
                    $params['createtime'] =  time();
                    if(ORG_CATE_ID > 0){
                        $params['type'] = 2;
                    }else{
                        $params['type'] = 1;
                    }
                    $params['adminid'] = AID;
                    $room = array();
                    $room['name'] = $params['name'];
                    $room['talk_id'] = $params['talk_id'];
                    unset($params['talk_id']);
                    $room['start_time'] = strtotime($params['start_time']);
                    unset($params['start_time']);
                    $room['content'] = $params['content'];
                    $room['is_show_ppt'] = $params['is_show_ppt'];
                    unset($params['is_show_ppt']);
                    $room['org_cate_id'] = ORG_CATE_ID;
                    $room['file'] = $params['file'];
                    unset($params['file']);
                    $result = $this->model->validate()->insertGetId($params);
                    if ($result === false) {
                        $this->error($this->model->getError());
                    }
                    $room_mdl = new ChatManagerLogic();
                    $room['room_id'] = $room_mdl->create();
                    $room_mdl->open($room['room_id']);
                    $room['type'] = 1;
                    $room['createtime'] = time();
                    $room['edu_learn_course_id'] = $result;
                    Db::name('chat_room')->insert($room);
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try{
                    $params['org_cate_id'] = ORG_CATE_ID;
                    $room = array();
                    $room['name'] = $params['name'];
                    $room['talk_id'] = $params['talk_id'];
                    unset($params['talk_id']);
                    $room['start_time'] = strtotime($params['start_time']);
                    unset($params['start_time']);
                    $room['content'] = $params['content'];
                    $room['is_show_ppt'] = $params['is_show_ppt'];
                    unset($params['is_show_ppt']);
                    $room['file'] = $params['file'];
                    unset($params['file']);
//                $params['author'] = str_replace('，', ',', $params['author']);
                    $result = $row->validate()->save($params);
                    if ($result === false) {
                        $this->error($row->getError());
                    }
                    Db::name('chat_room')->where('edu_learn_course_id', $ids)->update($room);
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }
        $room = Db::name('chat_room')->where('edu_learn_course_id', $ids)->find();
        $this->view->assign("row", $row);
        $this->view->assign("room", $room);
        return $this->view->fetch();
    }

    /**
     * 删除课程章节和聊天室
     * @param null $ids
     */
    public function del($ids = null)
    {
        if ($ids) {
            Db::startTrans();
            try{
                $res = $this->model->where('id', 'in', $ids)->delete();
                if($res===false){
                    $this->error($this->model->getError());
                }
                Db::name('chat_room')->where('edu_learn_course_id','in', $ids)->delete();
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success();
        }
        $this->error('编号错误！');
    }
    /**
     * 查看章节
     */
    public function chapter()
    {
        $course_id = $this->request->param('ids');
        $this->view->assign("ids", $course_id);
        //当前是否为关联查询
        $this->relationSearch = false;
        $this->model = new \app\admin\model\chat\Room;
        $this->searchFields = 'room.id,room.name';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2 = $this->getSelfDataWhere('room.org_cate_id');
            $total = $this->model
                ->with(['user','talk'])
                ->where($where)
                ->where('room.edu_learn_course_id',$course_id)
                ->where($where2)
//                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['user','talk'])
                ->where($where)
                ->where($where2)
                ->where('room.edu_learn_course_id',$course_id)
//                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加课程章节和聊天室
     * @return string
     * @throws Exception
     */
    public function chapteradd()
    {
        $course_id = $this->request->param('ids');
        $this->view->assign("ids", $course_id);
        $this->model =  new \app\admin\model\chat\Room;
        if ($this->request->isPost()) {
            $room = $this->request->post("room/a");
            if ($room) {
                if($room['start_time'] >= $room['end_time']){
                    $this->error('聊天室开启时间不得大于结束时间');
                }
                if($course_id > 0){
                    Db::startTrans();
                    try{
                        $room['edu_learn_course_id'] = $course_id;
                        $room['org_cate_id'] = ORG_CATE_ID;
                        $room['start_time'] = strtotime($room['start_time']);
                        $room['end_time'] = strtotime($room['end_time']);
                        $room_mdl = new ChatManagerLogic();
                        $room['room_id'] = $room_mdl->create();
                        $room['createtime'] = time();
                        $res = $this->model->insertGetId($room);
                        if($res === false){
                            $this->error($this->model->getError());
                        }
                        Db::commit();
                    }catch (Exception $e){
                        Db::rollback();
                        $this->error($e->getMessage());
                    }

                    $this->success();
                }
                $this->error('课程编号错误！');
            }
            $this->error('缺少必要参数！');
        }
        return $this->view->fetch();
    }

    /**
     * 编辑课程章节和聊天室
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public function chapteredit($ids = null)
    {
        $this->model = new \app\admin\model\chat\Room;
        $row_data = $this->model->get(['id' => $ids]);
        if (!$row_data) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $room = $this->request->post("room/a");
            if ($room) {
                $room['start_time'] = strtotime($room['start_time']);
                $room['end_time'] = strtotime($room['end_time']);
                if($room['start_time'] >= $room['end_time']){
                    $this->error('聊天室开启时间不得大于结束时间');
                }
                if($ids > 0){
                    $res = $this->model->save($room,['id'=>$ids]);
                    if($res === false){
                        $this->error($this->model->getError());
                    }
                    $this->success();
                }
                $this->error('编号错误！');
            }
            $this->error('缺少必要参数！');
        }
        $this->view->assign("room", $row_data);
        return $this->view->fetch();
    }

    /**
     * 删除课程章节和聊天室
     * @param null $ids
     */
    public function chapterdel($ids = null)
    {
        $this->model = new \app\admin\model\chat\Room;
        if ($ids) {
            $res = $this->model->where('id', 'in', $ids)->delete();
            if($res===false){
                $this->error($this->model->getError());
            }
            $this->success();
        }
        $this->error('编号错误！');
    }
}

